package com.army.stock.service.impl;

import com.army.stock.dao.ArmyCategoryDao;
import com.army.stock.domain.ArmyCategory;
import com.army.stock.service.ArmyCategoryService;
import com.javalife.common.domain.page.PaginatedArrayList;
import com.javalife.common.util.cache.LRUCache;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 14/12/29.
 */
public class ArmyCategoryServiceImpl implements ArmyCategoryService {

    private ArmyCategoryDao armyCategoryDao;

    public void setArmyCategoryDao(ArmyCategoryDao armyCategoryDao) {
        this.armyCategoryDao = armyCategoryDao;
    }

    private static LRUCache lruCache = new LRUCache(10000);

    public PaginatedArrayList getArmyCategoryPageInfo(int currentPage, int pageSize, Map<String, Object> map) {
        int startNum = (currentPage - 1) * pageSize;
        map.put("start", startNum);
        map.put("pageSize", pageSize);
        Integer count = armyCategoryDao.getCountArmyCategories(map);
        List<ArmyCategory> categories = armyCategoryDao.getArmyCategories(map);
        PaginatedArrayList<ArmyCategory> paginatedArrayList = new PaginatedArrayList<ArmyCategory>(currentPage, pageSize);
        paginatedArrayList.setTotalItem(count);
        paginatedArrayList.addAll(categories);
        return paginatedArrayList;
    }

    public void addArmyCategory(ArmyCategory armyCategory) {
        armyCategoryDao.insertArmyCategory(armyCategory);
    }

    public ArmyCategory getArmyCategoryById(Long id) {
        return armyCategoryDao.getArmyCategoryById(id);
    }

    public void updateArmyCategory(ArmyCategory armyCategory) {
        armyCategoryDao.updateArmyCategory(armyCategory);
    }

    public Integer delArmyCategory(Long id) {
        return armyCategoryDao.delArmyCategory(id);
    }

    public List<ArmyCategory> getAllArmyCategories() {
        List<ArmyCategory> dataList = armyCategoryDao.getArmyCategories(null);
        if (CollectionUtils.isNotEmpty(dataList)) {
            for (ArmyCategory armyCategory : dataList) {
                lruCache.put(armyCategory.getId(), armyCategory);
            }
        }
        return dataList;
    }

    public ArmyCategory getArmyCategoryByIdFromCache(Long categoryId) {
        ArmyCategory armyCategory = (ArmyCategory) lruCache.get(categoryId);
        if (armyCategory != null) {
            return armyCategory;
        }
        armyCategory = armyCategoryDao.getArmyCategoryById(categoryId);
        if (armyCategory != null) {
            lruCache.put(categoryId ,armyCategory);
        }
        return armyCategory;
    }


}
